package com.css.gateway.filter;

import com.css.common.core.constant.HttpStatus;
import com.css.common.core.constant.SecurityConstants;
import com.css.common.core.utils.*;
import com.css.common.core.constant.SsoConstants;
import com.css.common.redis.service.RedisImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.concurrent.TimeUnit;

/**
 * 网关鉴权
 *
 * @author css
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    private static final String LOGIN_USER_HEADER = "Accesstoken";

    @Autowired
    private RedisImpl redis;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();

        String url = request.getURI().getPath();
        // 跳过不需要验证的路径
        if (StringUtils.matches(url, SecurityUtils.WHITELIST)) {
            log.info("url设置了白名单");
            return chain.filter(exchange);
        }
        log.info("url未设置白名单");
        String token = getToken(request);
        if (StringUtils.isEmpty(token)) {
            return unauthorizedResponse(exchange, "令牌不能为空");
        }

        String yhxxHash = "";
        try {
            yhxxHash = redis.getMapValue(token, "yhxx");
            log.info(yhxxHash);
        } catch (Exception e) {
            log.info("根据tokenkey获取redis数据失败", e);
            return unauthorizedResponse(exchange, "无效的会话，或者会话已过期，请重新登录！");
        }
        if (GyUtils.isNull(yhxxHash)) {
            // 返回登录提示信息-401
            /*ResponseUtil.out(response,Result.error(401,"无效的会话，或者会话已过期，请重新登录！"));*/
            /*throw new ServiceException("无效的会话，或者会话已过期，请重新登录！");*/
            return unauthorizedResponse(exchange, "无效的会话，或者会话已过期，请重新登录！");
        } else {
            /*final Cookie cookie = new Cookie(LOGIN_USER_HEADER,token);
            cookie.setPath(SsoConstants.COOKIE_PATH);
            cookie.setHttpOnly(true);
            response.addCookie(cookie);*/
            //回写response
            ServletUtils.webFluxAddCookie(exchange.getResponse(), LOGIN_USER_HEADER, token, SsoConstants.COOKIE_PATH);
            //设置超时时间 7天
            /*RedisUtils.expire(token, 7, TimeUnit.DAYS);*/
            redis.expire(token, 7 * 24 * 60);
        }

        // 设置用户信息到请求
        addHeader(mutate, "yhxx", yhxxHash);
        // 内部请求来源参数清除
        removeHeader(mutate, SecurityConstants.FROM_SOURCE);
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    /*  *//**
     * 获取缓存key
     *//*
    private String getTokenKey(String token)
    {
        return CacheConstants.LOGIN_TOKEN_KEY + token;
    }*/

    /**
     * 获取请求token
     */
    private String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(LOGIN_USER_HEADER);
        if (GyUtils.isNull(token)) {
            HttpCookie cookie = request.getCookies().getFirst(LOGIN_USER_HEADER);
            if (cookie != null) {
                token = cookie.getValue();
            }
        }
        return token;
    }

    @Override
    public int getOrder() {
        return -200;
    }
}